package org.onvivals.admin.module.iot.controller;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.onvivals.common.param.PageParam;
import org.onvivals.common.web.PageResult;
import org.onvivals.common.web.Result;
import org.onvivals.module.iot.entity.IotFirmware;
import org.onvivals.module.iot.param.IotFirmwareParam;
import org.onvivals.module.iot.service.IIotFirmwareService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * IotFirmwareController
 *
 * @author weirdor (179946422@qq.com)
 * @version v1.0.0
 */
@Slf4j
@RestController
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@Tag(name = "固件")
@RequestMapping("/iotFirmware")
public class IotFirmwareController {

	private final IIotFirmwareService iotFirmwareService;

	@GetMapping
	@Operation(summary = "固件管理")
	public Result<PageResult<IotFirmware>> list(IotFirmwareParam param) {
		PageParam<IotFirmware, IotFirmwareParam> page = new PageParam<>(param);
		page.setDefaultOrder("create_time desc");
		IPage<IotFirmware> pa = iotFirmwareService.page(page, page.getWrapper());
		PageResult<IotFirmware> pageResult = new PageResult<>(pa.getRecords(), pa.getTotal());
		return Result.OK(pageResult);
	}

	/**
	 * 新增固件
	 */
	@PostMapping
	@Operation(summary = "新增固件")
	public Result<?> create(@RequestBody IotFirmware iotFirmware) {
		String productId = iotFirmware.getProductId();
		if (productId == null || productId.isEmpty()) {
			return Result.error("产品ID不能为空");
		}
		iotFirmwareService.save(iotFirmware);
		return Result.OK("新增固件成功");
	}

	/**
	 * 修改固件
	 */
	@PutMapping()
	@Operation(summary = "修改固件")
	public Result<?> update(@RequestBody IotFirmware iotFirmware) {
		String productId = iotFirmware.getProductId();
		if (productId == null || productId.isEmpty()) {
			return Result.error("产品ID不能为空");
		}
		iotFirmwareService.updateById(iotFirmware);
		return Result.OK("修改固件成功");
	}

	/**
	 * 删除固件
	 */
	@DeleteMapping("/{id}")
	@Operation(summary = "删除固件")
	public Result<?> delete(@PathVariable Long id) {
		iotFirmwareService.removeById(id);
		return Result.OK("删除固件成功");
	}

}
